package arrays;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 59.螺旋矩阵2
 * User: Li_yizYa
 * Date: 2025—03—20
 * Time: 20:55
 */
public class Solution5 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入要生成数组的维数n × n: ");
        int n = scan.nextInt();
        int[][] ret = generateMatrix(n);
        System.out.println("生成的" + n + "×" + n + "数组为: ");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(ret[i][j] + " ");
            }
            System.out.println();
        }
    }

    /**
     * 遵循左闭右开原则
     * @param n
     * @return
     */
    private static int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];
        int startX = 0, startY = 0;
        int loop = 0;
        int offset = 1;
        int count = 1;
        int i, j;

        while (loop < n / 2) {
            //顶部
            for (j = startX; j < n - offset; j++) {
                ret[startX][j] = count++;
            }
            //右侧
            for (i = startX; i < n - offset; i++) {
                ret[i][j] = count++;
            }
            //底部
            for (; j > startY; j--) {
                ret[i][j] = count++;
            }
            //左侧
            for (; i > startX; i--) {
                ret[i][j] = count++;
            }

            loop++;
            startX++;
            startY++;
            offset++;
        }

        if (n / 2 == 1) {
            ret[startX][startY] = count;
        }
        return ret;
    }
}
